/* Material specific application form settings */

$(document).ready(function() {
	/* 
	 * Setup the accordion
	 */
	$("#accordion").accordion({
		collapsible: false,
		active: 0,
		autoHeight: false
	});
	// Hack per disabilitare lo slot bottom al click del mouse
	var accordion = $( "#accordion" ).data("accordion");
	accordion._std_clickHandler = accordion._clickHandler;
	accordion._clickHandler = function( event, target ) {
		var clicked = $( event.currentTarget );
		if (! clicked.hasClass("slot_bottom"))
			this._std_clickHandler(event, target);
	};
	
	/* 
	 * Setup dataTables
	 */	
	var mTable = $('#lista').dataTable({
		"oLanguage"			: {"sUrl": "/js/dataTables/jquery.dataTables.it_IT.txt"},
		"bJQueryUI"			: true,
		"sDom"				:'<"H"lfr>t<"F"ip>', // 'frtip'
		"iDisplayLength"	: 10,
		"sPaginationType"	: "full_numbers",
		"bStateSave"		: true,
		"bAutoWidth"		: false,
		"aoColumns"			: [
			{ "mDataProp": "id", "sWidth": "50px" }, 
			{ "mDataProp": "name" }, 
			{ "mDataProp": null, "sWidth": "60px" } 
		],
	});
	
	// skins forms
	/*
	$(document).ready(function() {
		$('input[type="text"]').addClass("idleField");
		$('input[type="text"]').focus(function() {
			$(this).removeClass("idleField").addClass("focusField");
		});
		$('input[type="text"]').blur(function() {
			$(this).removeClass("focusField").addClass("idleField");
		});
	});
	*/
	
	// binds form submission and fields to the validation engine
	$("#detail").validationEngine();
	$("detail").submit(function(e) {
		e.preventDefault();
	});

	/*
	 * Dialog selezione categoria
	 */
	$('#X-browse-categories').dialog({
		width: 300,
		height: 200,
		modal: true,
		resizable: false,
		draggable: false,
		autoOpen: false,
		beforeClose: function () { doUpdateMaterialCategory(); },
		buttons: {
			Ok: function() { $(this).dialog('close'); }
		}
	});
	// Trigger click campo categoria
	$('#material_category').click(function(ev) {
		$('#X-browse-categories').dialog('open');
		$('#material_categories').attr('value', $('#material_category_id').val());
	});

	
}); // end of document.ready()


/*
 * Activates the material details accordion panel
 */ 
function openMaterialDetails(id) {
	$("#accordion").accordion('activate',1);
	getMaterialDetailsById(id);
}

/*
 * Aggiorna la categoria del materiale
 */

function doUpdateMaterialCategory() {
	var cat = $('#material_categories :selected');
	$('#material_category').attr('value', cat.text());
	$('#material_category_id').attr('value', cat.val());
}

/*
 * Ajax call for material details
 */
function getMaterialDetailsById(id) {
	waitingDialog({title: "Caricamento", message: "Interrogazione database<br>in corso..."});
	$.getJSON("/ajax/get-material-details-by-id", { 'id' : id, 'format' : 'json' }, function(data){
		closeWaitingDialog();
		
		console.log("Caricamento: " + data[0]['name'] + " (" + id + ")");
		$('#material_name').attr('value', data[0]['name'] ? data[0]['name'] : "" );
		$('#material_descr').attr('value', data[0]['description'] ? data[0]['description'] : "");
		$('#material_category_id').attr('value', data[0]['id_category'] ?  data[0]['id_category'] : 0);
		$('#material_category').attr('value', data['category'] ?  data['category'] : "Non categorizzato");
		$('#default_thickness').attr('value', data[0]['thickness'] ? data[0]['thickness'] : 0);
		$('#material_conductivity').attr('value', data['props']['thermal'][0] ? data['props']['thermal'][0]['conductivity'] : 0);
		$('#material_capacity').attr('value', data['props']['thermal'][0] ? data['props']['thermal'][0]['capacity'] : 0);
		$('#material_density').attr('value', data['props']['thermal'][0] ? data['props']['thermal'][0]['density'] : 0);
		$('#material_r_value').attr('value', data[0]['rvalue'] ? data[0]['rvalue'] : 0);
		$('#material_thermal_absorptance').attr('value', data['props']['physical'][0]['thermal_absorptance']);
		$('#material_solar_absorptance').attr('value', data['props']['physical'][0]['solar_absorptance']);
		$('#material_visible_absorptance').attr('value', data['props']['physical'][0]['visible_absorptance']);
		$('#material_roughness').attr('value', data['props']['physical'][0]['roughness']);
		//$('#material_has_ecarbon').attr('value', data[0]['has_ecarbon']);
		$('#material_co2').attr('value', data['props']['ecarbon'][0] ? data['props']['ecarbon'][0]['co2'] : 0);
		$('#material_conv_factor_name').attr('value', data['props']['ecarbon'][0] ? data['props']['ecarbon'][0]['conv_factor_name'] : 0);
		$('#material_ecarbon_source').attr('value', data['props']['ecarbon'][0] ? data['props']['ecarbon'][0]['source'] : 0);
		$('#material_assumption').attr('value', data['props']['ecarbon'][0] ? data['props']['ecarbon'][0]['assumption'] : 0);
		//$('#material_ecarbon_has_co2e').attr('value', data['props']['ecarbon'][0]['has_co2e']);
		$('#material_co2e').attr('value', data['props']['ecarbon'][0] ? data['props']['ecarbon'][0]['co2e'] : 0);

		// Azione: materiale precedente
		$("#material_prev").unbind('click');
		$("#material_prev").bind('click', function(e) {
			e.preventDefault();
			getMaterialDetailsById(data["prev"]);
		});

		// Azione: materiale successivo
		$("#material_next").unbind('click');
		$("#material_next").bind('click', function(e) {
			e.preventDefault();
			getMaterialDetailsById(data["next"]);
		});
		
		// Azione: elimina materiale
		$("#material_del").unbind('click');
		$("#material_del").bind('click', function(e) {
			e.preventDefault();
			answer = confirm("Confermi l'eliminazione di questo materiale?");
			if (answer) {
				$.ajax( {
					type: "GET",
					url: "/ajax/delete-material",
					data: "id=" + id,
					success: function() {
						getMaterialDetailsById(data["next"]);
					}
				});	
			}
		});

		// Azione: aggiungi (nuovo) materiale
		$("#material_add").unbind('click');
		$("#material_add").bind('click', function(e) {
			e.preventDefault();
			$("#detail").find(':input').each(function() {
				switch(this.type) {
					case 'password':
					case 'select-multiple':
					case 'select-one':
					case 'text':
					case 'textarea':
						$(this).val('');
						break;
					case 'checkbox':
					case 'radio':
						this.checked = false;
				}
			});
			// Importante
			id = "0";
		});

		// Azione: salva materiale
		$("#material_save").unbind('click');
		$("#material_save").bind('click', function(e) {
			e.preventDefault();	
			if (id == 0) {
				console.log("Saving a new material");
			} else {
				console.log("Updating an existing material");
			}

			$.ajax({
				type    : "POST",
				url     : "/preprocessor/materiali?function=SaveMaterial&format=json&id=" + id,
				data    : $("#detail").serialize(),
				success : function(response) {
					$("#detail").validationEngine("hideAll");
					if (response.esito > 0) {
						$("#material_name").validationEngine('showPrompt', response.messages, 'pass', 'topRight', true);
						// Aggiorniamo l'id dell'elemento visualizzato (importante in case di inserimento di un nuovo elemento)
						id = response.id;
					} 
					if (response.esito < 0) {
						$.each(response.messages, function(field, errorObj) {
							$.each(errorObj, function (errorType, errorMsg) {
								$("#" + field).validationEngine('showPrompt', errorMsg, 'error', 'topRight', true);
							});
						});
					}
					if (response.esito == 0){
						$("#material_name").validationEngine('showPrompt', response.messages, 'error', 'topRight', true);
					}
					//$("#detail").validationEngine("updatePromptsPosition");
				}
			});
		});
	});
}

